

<template>
  <el-form
      ref="formRef"
      :model="form"
      label-width="100px"
      style="text-align: center;padding-bottom:10px"
  >
    <el-upload
        :headers="headers"
        class="avatar-uploader"
        :action="getBaseUrl()+'sys/user/uploadImage'"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <el-button @click="handleConfirm" >确认更换</el-button>
  </el-form>
</template>

<script setup>
import {defineProps, ref} from "vue";
import requestUtil,{getBaseUrl} from "@/util/request";
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import store from "@/store";

const props=defineProps(
    {
      user:{
        type:Object,
        default:()=>{},
        required:true
      }
    }
)


const form=ref({
  id:-1,
  avatar:''
})

const formRef=ref(null)
const imageUrl=ref("")
const headers = ref({token: store.getters.GET_TOKEN})

form.value = props.user;
imageUrl.value = getBaseUrl() + 'image/useAvatar/' + form.value.avatar  //请求后端图片地址(回显原来的头像)

// 文件上传前
const beforeAvatarUpload =  (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('图片必须是jpg格式')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2M!')
  }
  return isJPG && isLt2M
}

// 上传文件到网页上，要回显图片
const handleAvatarSuccess=(res)=>{
  console.log(res.data)
  imageUrl.value=getBaseUrl()+res.data.src
  form.value.avatar=res.data.title;
}



// 文件上传的接口
const handleConfirm=async()=>{
  let result=await requestUtil.post("sys/user/updateAvatar",form.value);

  if(result.code=== '0'){
    ElMessage.success("执行成功！")
    store.commit("SET_USERINFO",form.value)
  }else{
    ElMessage.error(result.msg);
  }
}


</script>

<style scoped lang="scss">

</style>